package kofman.test.info;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.*;
import java.io.*;
import java.util.Calendar;

import android.R.integer;
import android.util.Log;
import android.widget.LinearLayout.LayoutParams;

import kofman.test.cps.TableAdapter;
import kofman.test.cps.testMyListView;
import kofman.test.cps.TableAdapter.TableCell;
import kofman.test.cps.TableAdapter.TableRow;
public class checkStockDate {
		static String Today="";//紀錄今天日期
		static final String[] Webdns={"http://money.hinet.net/z/ze/zec/zec.djhtm","http://www.emega.com.tw/z/ze/zeb/zeb.asp.htm"};
		static int[] prices=new int[4];//分紀錄開盤 最高 最低 收盤 四種價錢
		String[] title={"名稱","代號","股價","時間","其他"};
	    static final int[] port={80};
		static Date d=new Date();
	    static String s;
		ArrayList<TableRow> table;

	    static private int try_number=1;
	    static DateFormat formateYearMonthDay=new SimpleDateFormat("yyyy-MM-dd");//設定時間格式HH 24小時時制
	    static DateFormat formate1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設定時間格式HH 24小時時制
//	    static conMySQL con=null;
	    static java.text.DecimalFormat df=new java.text.DecimalFormat("#.##");//小數點後兩位
	    static java.text.DecimalFormat df2=new java.text.DecimalFormat("#.###");//小數點後三位
		static boolean alreadySentErrMeaasge=false;//查看是否已經發錯誤訊息通知
	    public static void main(String[] args) { 
			checkStockDate check=new checkStockDate();
			Today=formateYearMonthDay.format(new Date());			
			}

		public String[] getTodayPrice(String id) {
			String [] value=new String[3];
			try{
				URL url=new URL("http://tw.stock.yahoo.com/q/q?s="+id);
				BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"BIG5"));
				String line;
				int count=0;
		    	String pattern1 = "((.)*<td){1}.(align=){1}(.)*(nowrap>){1}(<b>|<font color=#ff0000|<font color=#009900>)?";
		    	String pattern2 = "(</b>)?(</td>){1}";
//		    	String pattern3="(△|▽|<font color=#000000>)?";
		    	while((line=reader.readLine())!=null){
		    		if(line.indexOf("<td align=\"")!=-1){
		    			count++;
		    			line=line.replaceAll(pattern1, "").replaceAll(pattern2, "");
//		    			System.out.println(line);
		    			switch (count) {
						case 1:
							//時間
							value[0]=line;
							break;
						case 2:
							//成交價
							value[1]=line;
							break;
						case 5:
							//漲跌停
//							System.out.println(line);
							value[2]=returnWord(line);
//							System.out.println("Return:"+value[2]);
							break;
						}
		    		}
		    	}
			}catch (MalformedURLException e) {
				// TODO: handle exception
			}catch (IOException e) {
				// TODO: handle exception
			}
			return value;
		}
		public String returnWord(String line){
//			System.out.println(line);
	    	String pattern="(△|▽|<font color=#000000>|▲)?";
			if(line.indexOf("△")!=-1){
				return ("UP "+line.replaceAll(pattern, ""));
			}else if(line.indexOf("▽")!=-1){
				return ("DOWN "+line.replaceAll(pattern, ""));
			}else if(line.indexOf("▲")!=-1){
				return ("M_UP "+line.replaceAll(pattern, ""));
			}else if(line.indexOf("▼")!=-1){
				return("M_DOWN "+line.replaceAll(pattern, ""));
			}else{
				return(line.replaceAll(pattern, ""));
			}
			
		}
		public void getStockPrice(){
			try{ 			
				URL url=new URL(Webdns[1]);
				int count=0;
				s=formate1.format(new Date());
				while(count<try_number){		
					int countline=0;
					//HttpURLConnection huc=(HttpURLConnection)url.openConnection();
					BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"BIG5"));
					String line;
			    	System.out.println("Get Information form Web!");
			    	String pattern1 = "(<TD|<td){1}.(class=\"t3){1}(n|t){1}(1|0)?(\"){1}(>){1}";
			    	String pattern2 = "(</TD>|</td>){1}";
			    	String pattern3 = "(GenLink2stk){1}|<a href=\"javascript:Link2Stk(.)*\">";
			    	String pattern4 = "(,){1}";
			    	String pattern4_1="[0-9]{1,4}[0-1]{1}";
			    	String pattern5 = "(;)?(</a>)?";
			    	String pattern6="((.)*\\((AS)){1}|\\)";
			    	int linecount=0;
			    	while((line=reader.readLine())!=null){
						if(line.indexOf("GenLink2stk")!=-1|line.indexOf("javascript:Link2Stk")!=-1){
//							linecount=0;
							String[] newline=line.replaceAll(pattern3, "").split(pattern4);
							String[] value=new String[2];
							for(int i1=0;i1<newline.length;i1++){
								if(i1==0){
									value[0]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");

									System.out.print(" 代號："+value[0]);
//									value[0]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
								}else{
									value[1]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
									System.out.print(" 名稱："+value[1]);
//									value[1]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
								}
								
								//System.out.print(newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,""));	
							}
//							System.out.println(line.replaceAll(pattern2, ""));
						}
						else 
							if(line.indexOf("<TD class=\"t3")!=-1|line.indexOf("<td class=\"t3")!=-1){
							linecount++;
							String word="";
							int modnum=(linecount-1)%8;
							switch(modnum){
								case 0:
									word="日期：";
									break;
								case 2:
									word=" 現金股利：";
									break;
								case 3:
									word=" 盈餘配股：";
									break;
								case 4:
									word=" 公績配股:";
									break;
								case 5:
									word=" 現金增資:";
									break;
								case 6:
									word=" 承銷價:";
									break;
								case 7:
									linecount=0;
									word="現金股利發放日:";
									break;
							}
							
							String httpword=line.replaceAll(pattern1, "").replaceAll(pattern2, "");
							if(httpword.equals("&nbsp;")){
								httpword="無資訊";
							}
							if(modnum==7){
								System.out.println(" "+modnum+word+httpword);
							}else if (modnum==1) {
							}else{
								if(!httpword.contains("<tr>")){
									System.out.print(" "+modnum+":"+word+httpword);
								}
							}
						
						}
						
					}
					reader.close();
					count++;
				}
				}catch (Exception e) {

			}

	
			
		}
		
		public int getLinenumber(){
	    	int linecount=0;
			try{ 			
				URL url=new URL(Webdns[1]);
				int count=0;
				s=formate1.format(new Date());
				while(count<try_number){			
					int countline=0;
					//HttpURLConnection huc=(HttpURLConnection)url.openConnection();
					BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"BIG5"));
					String line;

			    	String pattern3 = "(GenLink2stk){1}|<a href=\"javascript:Link2Stk(.)*\">";
			    	String pattern4 = "(,){1}";
			    	String pattern5 = "(;)?(</a>)?";
			    	String pattern6="((.)*\\((AS)){1}|\\)";

			    	while((line=reader.readLine())!=null){
						if(line.indexOf("GenLink2stk")!=-1|line.indexOf("javascript:Link2Stk")!=-1){
//							linecount=0;
							String[] newline=line.replaceAll(pattern3, "").split(pattern4);
//							String value;
							for(int i1=0;i1<newline.length;i1++){
								if(i1==0){
									String value=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
									if(value.length()==4){
										linecount++;
									}
								}
								
								//System.out.print(newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,""));	
							}

						}

						
						}
					reader.close();
					count++;
				}
				}catch (Exception e) {
			}
			return linecount; 

	
			
		}	
		public ArrayList<TableRow> setPriceRows(){
			testMyListView test=new testMyListView();
			table=test.initTable();
//			Log.i("Stock", "Table Size"+table.size());
//			Log.i("Stock","Get PriceRow");
			try{ 			
				URL url=new URL(Webdns[1]);
				int count=0;
				s=formate1.format(new Date());
				while(count<try_number){
					//HttpURLConnection huc=(HttpURLConnection)url.openConnection();
					BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"BIG5"));
					String line;
					
			    	String pattern1 = "(<TD|<td){1}.(class=\"t3){1}(n|t){1}(1|0)?(\"){1}(>){1}";
			    	String pattern2 = "(</TD>|</td>){1}";
			    	String pattern3 = "(GenLink2stk){1}|<a href=\"javascript:Link2Stk(.)*\">";
			    	String pattern4 = "(,){1}";
//			    	String pattern4_1="[0-9]{1,4}[0-1]{1}";
			    	String pattern5 = "(;)?(</a>)?";
			    	String pattern6="((.)*\\((AS)){1}|\\)";
			    	int linecount=0;
			    	while((line=reader.readLine())!=null){
			    		TableCell[] cells = new TableCell[5];// 每行5个单元
			    		int gate=0;//看是否需要紀錄
						if(line.indexOf("GenLink2stk")!=-1|line.indexOf("javascript:Link2Stk")!=-1){
							String[] newline=line.replaceAll(pattern3, "").split(pattern4);
							String[] value=new String[2];
							for(int i1=0;i1<newline.length;i1++){
								if(i1==0){
//									Log.i("Stock", "i1=0");
									value[0]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
									if(value[0].length()==4){
										linecount++;
										gate=1;//正常股票代號 開始紀錄
										cells[0]=new TableCell(value[0],test.titles[0].width, LayoutParams.FILL_PARENT, TableCell.STRING);																				
										Log.i("Stock"," 代號："+value[0]);
									}
//									value[0]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
								}else{
									value[1]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
									Log.i("Stock"," 名稱："+value[1]);
									if(gate==1){
										cells[1]=new TableCell(value[1],test.titles[1].width, LayoutParams.FILL_PARENT, TableCell.STRING);
										Log.i("Stock", "info:"+value[1]);
										String[] price=getTodayPrice(value[0]);
										for (int i = 0; i < price.length; i++) {
											int j=i+2;
											Log.i("Stock"," Other："+price[i]);
											cells[j]=new TableCell(price[i],test.titles[j].width, LayoutParams.FILL_PARENT, TableCell.STRING);
											if(i==2){
//												Log.i("Stock", "Equal to  prices length-1"+i);
												table.add(new TableRow(cells));
											}
										}
//										System.out.print(" 名稱："+value[1]);
										
									}
								}

								
								
								//System.out.print(newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,""));	
							}
//							System.out.println(line.replaceAll(pattern2, ""));
						}
						else 
							if(line.indexOf("<TD class=\"t3")!=-1|line.indexOf("<td class=\"t3")!=-1){
							linecount++;
							String word="";
							int modnum=(linecount-1)%8;
							switch(modnum){
								case 0:
									word="日期：";
									break;
								case 2:
									word=" 現金股利：";
									break;
								case 3:
									word=" 盈餘配股：";
									break;
								case 4:
									word=" 公績配股:";
									break;
								case 5:
									word=" 現金增資:";
									break;
								case 6:
									word=" 承銷價:";
									break;
								case 7:
									linecount=0;
									word="現金股利發放日:";
									break;
							}
							
							String httpword=line.replaceAll(pattern1, "").replaceAll(pattern2, "");
							if(httpword.equals("&nbsp;")){
								httpword="無資訊";
							}
							if(modnum==7){
//								System.out.println(" "+modnum+word+httpword);
							}else if (modnum==1) {
							}else{
								if(!httpword.contains("<tr>")){
//									System.out.print(" "+modnum+":"+word+httpword);
								}
							}
						
						}
						
					}
					reader.close();
					count++;
				}
				}catch (Exception e) {
					Log.i("Stock", e.toString());
			}
			Log.i("Stock","123:"+table.size());
			return table;
					//			return tableCells;
	
			
		}

		

		public void GetStockTime(){
			for(int i=0;i<Webdns.length;i++){	
				try{ 			
					URL url=new URL(Webdns[i]);
					int count=0;
					s=formate1.format(new Date());
					String tempDate=formateYearMonthDay.format(new Date());
					while(count<try_number){
						int countline=1;
						//HttpURLConnection huc=(HttpURLConnection)url.openConnection();
						BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"BIG5"));
						String line;
//				    	System.out.println("Get Information form Web!");
				    	String pattern1 = "(<TD|<td){1}.(class=\"t3){1}(n|t){1}(1|0){1}(_rev)?(\"){1}(.)?(nowrap)?(>){1}";
				    	String pattern2 = "(</TD>|</td>){1}";
				    	String pattern3 = "(GenLink2stk){1}";
				    	String pattern4 = "(,){1}";
				    	String pattern5 = "(;)?";
				    	String pattern6="((.)*\\((AS)){1}|\\)";
				    	int linecount=5;
				    	while((line=reader.readLine())!=null){
							if(line.indexOf("GenLink2stk")!=-1){
//								linecount=0;
								String[] newline=line.replaceAll(pattern3, "").split(pattern4);
								for(int i1=0;i1<newline.length;i1++){
									if(i1==0){
										System.out.print("代號：");
									}else{
										System.out.print(" 名稱：");
									}
									System.out.print(newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,""));	
								}
//								System.out.println(line.replaceAll(pattern2, ""));
							}
							else if(line.indexOf("<TD class=\"t3")!=-1|line.indexOf("<td class=\"t3")!=-1){
								String word="";
								switch(linecount%4){
									case 0:
										word=" 開會時間：";
										break;
									case 1:
										word=" 開會地點：";
										break;
									case 2:
										word=" 改選:";
										break;
									case 3:
										word=" 性質:";
										break;
								}
								
								if(linecount%4!=3){
									System.out.print(linecount+":"+word+line.replaceAll(pattern1, "").replaceAll(pattern2, ""));
								}else {
									System.out.println(linecount+":"+word+line.replaceAll(pattern1, "").replaceAll(pattern2, ""));
								}
								linecount++;
							}
							countline++;
						}
						reader.close();
						count++;
					}
					}catch (Exception e) {

				}
			}
			
		}


		//get WAN IP from http://checkip.dyndns.org
		public String readIP(){
			String result=null;
			try{
			URL url=new URL("http://checkip.dyndns.org");
			BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream()));
			String line;
	    	//System.out.println("Get Information form Web!");
			while((line=reader.readLine())!=null){
				String[] temp=getStrings(line, ":");
				//System.out.println(temp[0]);
				//System.out.println(temp[1]);
				temp=getStrings(temp[1], "<");
				result=temp[0].replace(" ", "");
				//System.out.println(temp[1]);
			}
			}catch(Exception e){
				e.printStackTrace();
				
			}
			return result;
		}	
		
		
		public  static String[] getStrings(String oldstr,String sym){
			String[] a=null;
			StringTokenizer st=new StringTokenizer(oldstr,sym);
			int n=st.countTokens();
			a=new String[n];
			int i=0;
			while(st.hasMoreTokens()){
				a[i]=st.nextToken();
				i++;
			}
			return a;
		}
		
		public  static java.util.Vector<String> checkStrCondition(String[] oldArray){
			String[] a=null;
			java.util.Vector<String> temp=new java.util.Vector<String>(0);
			for (int i = 0; i < oldArray.length; i++) {
				if((oldArray[i].indexOf("#")==-1)&&(oldArray[i].length()>6)){
					temp.add(oldArray[i]);
				}
			}
			return temp;
		}
		//將千元轉換成億
		public static String changeToE(int number){
			 return df2.format((Double.valueOf(number))/100000);
		}

		//檢查是否為星期六或是日（是的話就不作）
		public boolean CheckWeeks(){
		    DateFormat formateDay2=new SimpleDateFormat("E",java.util.Locale.ENGLISH);//設定時間格式(轉換成millsec)
		    Date date=new Date();
		    String week=formateDay2.format(date);
			if(week.equals("Sat")||week.equals("Sun")){
				return false;
			}else{
				return true;
			}
			
		}
		




}
